﻿/*
COPYRIGHT (C) 2009 EPISERVER AB

THIS FILE IS PART OF MAPPED PAGE PROVIDER FOR EPISERVER CMS.
MAPPED PAGE PROVIDER FOR EPISERVER CMS IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

MAPPED PAGE PROVIDER FOR EPISERVER CMS IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH MAPPED PAGE PROVIDER FOR EPISERVER CMS. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EPiServer.Research.PageProviders
{
    internal class PageProviderCache
    {
        const int MAXMAPPINGS = 10000;
        private Dictionary<string, PageProviderMapping> KeyMap;
        private Dictionary<int, PageProviderMapping> IdMap;
        private Dictionary<Guid, PageProviderMapping> GuidMap;
        private List<PageProviderMapping> baseList;

        internal PageProviderMapping GetFromCache(string Key)
        {
            PageProviderMapping ppm = null;
            KeyMap.TryGetValue(Key, out ppm);
            return ppm;
        }
        internal PageProviderMapping GetFromCache(int Id)
        {
            PageProviderMapping ppm = null;
            IdMap.TryGetValue(Id, out ppm);
            return ppm;
        }
        internal PageProviderMapping GetFromCache(Guid g)
        {
            PageProviderMapping ppm = null;
            GuidMap.TryGetValue(g, out ppm);
            return ppm;
        }

        internal void AddToCache(PageProviderMapping pm)
        {
            KeyMap.Add(pm.Key, pm);
            IdMap.Add(pm.ID, pm);
            GuidMap.Add(pm.Guid, pm);
            baseList.Add(pm);
            if (baseList.Count > MAXMAPPINGS)
            {
                PageProviderMapping m = baseList[0];
                RemoveFromCache(m);
            }
        }

        internal void RemoveFromCache(PageProviderMapping m)
        {
            baseList.Remove(m);
            KeyMap.Remove(m.Key);
            IdMap.Remove(m.ID);
            GuidMap.Remove(m.Guid);
        }

        internal PageProviderCache()
        {
            KeyMap = new Dictionary<string, PageProviderMapping>(MAXMAPPINGS);
            IdMap = new Dictionary<int, PageProviderMapping>(MAXMAPPINGS);
            GuidMap = new Dictionary<Guid, PageProviderMapping>(MAXMAPPINGS);
            baseList = new List<PageProviderMapping>(MAXMAPPINGS);
        }
    }
}
